/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.policysyn;

import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Dpiendpointbean;
import cn.net.greenet.db.bean.Messageincominglog;
import cn.net.greenet.db.bean.Policyrepositoryinstance;
import cn.net.greenet.db.bean.Rvcheckstatus;
import cn.net.greenet.db.bean.Versionreported;
import cn.net.greenet.db.bean.VersionreportedId;
import com.ambimmort.umessage.uc.incoming.xC2;
import com.ambimmort.umessage.util.HexUtil;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author hedingwei
 */
public class ReportedVersionNormalizer {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void normalize(int dpiIdint, Session session) throws IOException, ParseException {
        String dpiId = dpiIdint + "";


        Object rvcheckstatusObject = session.get(Rvcheckstatus.class, Integer.parseInt(dpiId));
        long lastCheckTime = 946656000000l; // 2000年1月1日 00:00:00
        if (rvcheckstatusObject == null) {
            Rvcheckstatus status = new Rvcheckstatus(Integer.parseInt(dpiId), new Date(System.currentTimeMillis()));
            Transaction tx = null;
            try {
                tx = session.beginTransaction();
                session.save(status);
                tx.commit();
            } catch (Exception e) {
                e.printStackTrace();
                tx.rollback();
            }
        } else {
            Rvcheckstatus status = (Rvcheckstatus) rvcheckstatusObject;
            lastCheckTime = status.getLastCheckTime().getTime();
        }

        Date lastTimePtr = new Date(lastCheckTime);

        try {
            Versionreported bean = null;
            Dpiendpointbean dpiBean = (Dpiendpointbean) session.get(Dpiendpointbean.class, Integer.parseInt(dpiId));
            Map<String, Integer> map = new HashMap<String, Integer>();
            Policyrepositoryinstance priPtr = null;
            for (Object piObj : dpiBean.getPolicyrepositoryinstances()) {
                priPtr = (Policyrepositoryinstance) piObj;
                map.put(priPtr.getPolicyrepositorytype().getMessageType(), priPtr.getId());
            }

            System.out.println("==>[Function GetReportedVersion]");
            System.out.println("=>DPI Configured map: " + dpiBean.getName());
            System.out.println("=>" + map.toString());
            Messageincominglog log = null;
            Query q1 = session.createQuery("SELECT log FROM Messageincominglog AS log where log.dpiendpointbean.id=:dpiId and log.messageType=:messageType and log.time > :lastCheckTime ORDER BY log.time");
            q1.setParameter("messageType", "0xC2");
            q1.setParameter("dpiId", dpiBean.getId());
            q1.setParameter("lastCheckTime", lastTimePtr);
            List c2log = q1.list();

            if (!c2log.isEmpty()) {
                for (Object logObj : c2log) {
                    log = (Messageincominglog) logObj;
                    Transaction tx = null;
                    xC2 c2 = new xC2();
                    try {
                        c2.parseBinary(log.getPacket());
                    } catch (Exception e) {
                        System.out.println("==>[Packet Exception][IN][C2][LOG:" + log.getId() + "][" + dpiBean.getName() + "][" + dpiBean.getMasterIp() + "]");
                        continue;
                    }
                    System.out.println("=>logid=" + log.getId());
                    System.out.println("=>parsedC2=" + c2.getPolicys().toString());
                    String msgType = null;
                    for (xC2.Message m : c2.getPolicys()) {
                        msgType = "0x" + HexUtil.getHex(m.getMessageType().toByte());
                        System.out.println("=>processing:logid:" + log.getId() + ",msgType:" + msgType);
                        if (map.containsKey(msgType)) {
                            try {
                                tx = session.beginTransaction();
                                Versionreported vr = new Versionreported();
                                vr.setDpiendpointbean(dpiBean);
                                vr.setPolicyrepositoryinstance((Policyrepositoryinstance) session.get(Policyrepositoryinstance.class, map.get(msgType)));
                                VersionreportedId vid = new VersionreportedId(Integer.parseInt(dpiId), map.get(msgType));
                                vr.setId(vid);
                                vr.setMessageSerialNo(m.getMessageSerialNo().toLong());
                                vr.setReportTime(log.getTime());
                                session.saveOrUpdate(vr);
                                session.createQuery("update Rvcheckstatus r set r.lastCheckTime=:time where r.dpiId=:dpiId").setParameter("time", new Date(System.currentTimeMillis())).setParameter("dpiId", Integer.parseInt(dpiId)).executeUpdate();
                                System.out.println("=>saveOrUpdated:<" + vr.getId().getDpiendPointBeanId() + "," + vr.getId().getPolicyRepositoryInstanceId() + ">");
                                tx.commit();
                                session.evict(vr);
                            } catch (Exception e) {
                                e.printStackTrace();
                                tx.rollback();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw e;
        }
    }
}
